<?php

namespace App\Http\Controllers\Auth;

use App\Models\IntegralLog;
use App\Models\User;
use App\Models\Upload;
use App\Models\Customer;
use App\Models\Cart;
use App\Models\BusinessSetting;
use App\Models\UserLevel;
use App\OtpConfiguration;
use App\Http\Controllers\Controller;
use App\Http\Controllers\OTPVerificationController;
use App\Notifications\EmailVerificationNotification;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Cookie;
use Session;
use Nexmo;
use Twilio\Rest\Client;
use function dd;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $res = Validator::make($data, [
            'name' => 'required|string|max:255',
            'password' => 'required|string|min:6|confirmed',
//            'identity_card_front' => 'required',
//            'identity_card_back' => 'required',
        ]);
        return $res;
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {

//        if (filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {

//        $user = User::create([
//            'name' => $data['name'],
//            'phone' => $data['email'],
//                'email' => $data['email'],
//                'identity_card_front' => $data['identity_card_front'],
//                'identity_card_back' => $data['identity_card_back'],
//            'password' => Hash::make($data['password']),
//        ]);

//             Upload::where('id', $data['identity_card_back'])
//            ->update([
//                'user_id' => $user->id
//            ]);
//            Upload::where('id', $data['identity_card_front'])
//            ->update([
//                'user_id' => $user->id
//            ]);
//        }
//        else {
//            if (addon_is_activated('otp_system')){

                $user = User::create([
                    'name' => $data['name'],
                    'phone' => '+'.$data['country_code'].$data['phone'],
                    'password' => Hash::make($data['password']),
                    'identity_card_front' => $data['identity_card_front'],
                    'identity_card_back' => $data['identity_card_back'],
//                    'verification_code' => rand(100000, 999999),
                ]);
//
//                $otpController = new OTPVerificationController;
//                $otpController->send_code($user);
//            }
//        }
        Upload::where('id', $data['identity_card_back'])
            ->update([
                'user_id' => $user->id
            ]);
        Upload::where('id', $data['identity_card_front'])
            ->update([
                'user_id' => $user->id
            ]);
        if(session('temp_user_id') != null){
            Cart::where('temp_user_id', session('temp_user_id'))
                    ->update([
                        'user_id' => $user->id,
                        'temp_user_id' => null
            ]);

            Session::forget('temp_user_id');
        }
//        dump($user);
        $user->identity_card_front = $data['identity_card_front'];
        $user->identity_card_back = $data['identity_card_back'];
        $user->save();
        $user->referral_code = $this->set_invitation();
//        if(Cookie::has('referral_code')){
//            $referral_code = Cookie::get('referral_code');
//            $referred_by_user = User::where('id', $referral_code)->first();
//            if($referred_by_user != null){
//                $user->referred_by = $referred_by_user->id;
//                $user->pid = $referred_by_user->id;
//
//            }
//        }
        if($data['referral_code']){
            $referral_code = $data['referral_code'];
            $referred_by_user = User::where('referral_code', $referral_code)->first();
            if($referred_by_user != null){
                $user->referred_by = $referred_by_user->id;
                $user->pid = $referred_by_user->id;
                $user->save();
            }else{
                flash(translate('referral user not exsit'))->warning();
                return;
            }
        }else{
            if(Cookie::has('referral_code')){
                $referral_code = Cookie::get('referral_code');
                $referred_by_user = User::where('referral_code', $referral_code)->first();
                if($referred_by_user != null){
                    $user->referred_by = $referred_by_user->id;
                    $user->pid = $referred_by_user->id;
                    $user->save();
                }
            }
        }

        $user->save();
        //邀请送积分
        if($user->pid){
            $parentLevel = UserLevel::where('id',$referred_by_user->level)->first();
            if($parentLevel){
                if($parentLevel->invite_integral){
                    IntegralLog::insert([
                        'user_id' => $user->pid,
                        'number' => $parentLevel->invite_integral,
                        'order_id' => 0,
                        'type' => 2,
                        'pm' => 1,
                    ]);
                    User::where('id',$user->pid)->increment('integral',$parentLevel->invite_integral);
                }
                if($parentLevel->user_integral){
                    IntegralLog::insert([
                        'user_id' => $user->id,
                        'number' => $parentLevel->user_integral,
                        'order_id' => 0,
                        'type' => 3,
                        'pm' => 1,
                    ]);
                    User::where('id',$user->id)->increment('integral',$parentLevel->user_integral);
                }
            }
        }
        return $user;
    }

    public function set_invitation($len = 8,$chars = null){
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return strtoupper($str);
    }


    public function register(Request $request)
    {
        if (filter_var($request->email, FILTER_VALIDATE_EMAIL)) {
            if(User::where('email', $request->email)->first() != null){
                flash(translate('Email or Phone already exists.'));
                return back();
            }
        }
        elseif (User::where('phone', $request->phone)->first() != null) {
            flash(translate('Phone already exists.'));
            return back();
        }
//        if ( $request->identity_card_front == NULL )
//        {
//            flash(translate('Identity Card Front Not Allow Empty!'))->error();
//            return back();
//        }
//        if ( $request->identity_card_back == NULL )
//        {
//            flash(translate('Identity Card Back Not Allow Empty!'))->error();
//            return back();
//        }
        $this->validator($request->all())->validate();

        $user = $this->create($request->all());

        $this->guard()->login($user);

        if($user->email != null){
            if(BusinessSetting::where('type', 'email_verification')->first()->value != 1){
                $user->email_verified_at = date('Y-m-d H:m:s');
                $user->save();
                flash(translate('Registration successful.'))->success();
            }
            else {
                try {
                    $user->sendEmailVerificationNotification();
                    flash(translate('Registration successful. Please verify your email.'))->success();
                } catch (\Throwable $th) {
                    $user->delete();
                    flash(translate('Registration failed. Please try again later.'))->error();
                }
            }
        }

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    protected function registered(Request $request, $user)
    {
        if ($user->email == null) {
//            return redirect()->route('home');
            return redirect()->route('verification');
        }elseif(session('link') != null){
            return redirect(session('link'));
        }else {
            return redirect()->route('home');
        }
    }
}
